package com.zlx.mall.biz.combo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zlx.mall.base.entity.*;
import com.zlx.mall.base.service.*;
import com.zlx.mall.basic.common.enums.NotDeteteEnum;
import com.zlx.mall.basic.web.model.BaseResponse;
import com.zlx.mall.biz.combo.model.*;
import com.zlx.mall.biz.combo.service.IComboService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author xiatian
 * @Date 2025/3/23 星期日 12:30
 * @注释
 */
@Slf4j
@Service
public class ComboServiceImpl implements IComboService {
    @Autowired
    private IScUserService scUserService;
    @Autowired
    private IScComboService scComboService;
    @Autowired
    private IScComboCategoryService scComboCategoryService;
    @Autowired
    private IScCategoryService scCategoryService;
    @Autowired
    private IScGoodsService scGoodsService;
    @Autowired
    private IScGoodsMatchService scGoodsMatchService;


    @Override
    public BaseResponse list(String selectCode) {
        BaseResponse response = BaseResponse.success();
        if (StrUtil.isEmpty(selectCode)) return response;
        ScCombo combo = scComboService.getOne(new QueryWrapper<ScCombo>().eq(ScCombo.SELECT_CODE, selectCode).eq(ScCombo.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()));
        if (null == combo) return response;
        List<ScComboCategory> comboCategoryList = scComboCategoryService.list(new QueryWrapper<ScComboCategory>().eq(ScComboCategory.COMBO_ID, combo.getId()).eq(ScComboCategory.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()));
        if (comboCategoryList.isEmpty()) return response;

        Map<Long, List<ScComboCategory>> oneCategoryMap = comboCategoryList.stream().collect(Collectors.groupingBy(ScComboCategory::getCategoryId));
        log.info("根据一级分类分组={}", oneCategoryMap);
        List<ComboListResponse> responses = new ArrayList<>();
        for (Map.Entry<Long, List<ScComboCategory>> entry : oneCategoryMap.entrySet()) {
            ComboListResponse oneCategoryResponse = new ComboListResponse();
            Long categoryId = entry.getKey();
            oneCategoryResponse.setId(categoryId);
            ScCategory category = scCategoryService.getOne(new QueryWrapper<ScCategory>().eq(ScCategory.ID, categoryId).eq(ScCategory.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()));
            if (ObjectUtil.isNull(category)) continue;
            oneCategoryResponse.setName(category.getName());
            oneCategoryResponse.setCategoryImg(category.getCategoryImg());
            oneCategoryResponse.setSort(category.getSort());
            oneCategoryResponse.setUpgrade(combo.getUpgrade());
            oneCategoryResponse.setAddBuy(combo.getAddBuy());
            List<ScComboCategory> oneCategoryList = entry.getValue();
            log.info("一级分类={}，对应的二级分类={}",categoryId, oneCategoryList);

            List<SubCategory> subCategoryList = new ArrayList<>();
            Map<Long, List<ScComboCategory>> twoCategoryMap = oneCategoryList.stream().collect(Collectors.groupingBy(ScComboCategory::getSubCategoryId));
            for (Map.Entry<Long, List<ScComboCategory>> twoCategoryEntry : twoCategoryMap.entrySet()) {
                Long subCategoryId = twoCategoryEntry.getKey();
                List<ScComboCategory> twoCategoryList = twoCategoryEntry.getValue();
                log.info("二级分类={}，分组对应的列表={}",subCategoryId, subCategoryList);
                //遍历每个具体的二级分类
                SubCategory subCategory = new SubCategory();
                subCategory.setId(subCategoryId);
                ScCategory scCategory = scCategoryService.getOne(new QueryWrapper<ScCategory>().eq(ScCategory.ID, categoryId).eq(ScCategory.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()));
                if (ObjectUtil.isNull(scCategory)) continue;
                subCategory.setName(scCategory.getName());

                log.info("二级分类={}，下面具体的商品={}", subCategory.getId(), twoCategoryList);
                //subCategory.setSelectGoods(); TODO:查询该二级类目配置的加购的商品
                subCategory.setUpgrade(selectUpgrade(subCategoryId,twoCategoryList));
                subCategory.setCategoryImg(scCategory.getCategoryImg());
                subCategory.setGoodsIds(twoCategoryList.stream().map(ScComboCategory::getGoodsId).collect(Collectors.toList()));
                subCategory.setSort(scCategory.getSort());
                subCategoryList.add(subCategory);
            }
            oneCategoryResponse.setSubCategoryList(subCategoryList);
            responses.add(oneCategoryResponse);
        }
        // 1. 对ComboListResponse主列表按sort字段排序（升序）
        responses.sort(Comparator.comparingInt(ComboListResponse::getSort));

        // 2. 对每个子分类列表排序（升序）
        responses.forEach(items -> {
            if (items.getSubCategoryList() != null) {
                items.getSubCategoryList().sort(Comparator.comparingInt(SubCategory::getSort));
            }
        });
        return BaseResponse.success(responses);
    }

    @Override
    public List<GoodsUpgradeResponse> goodsUpgrade(Long subCategoryId) {
        log.info("查看二级类目下的升级商品");
        List<ScComboCategory> list = scComboCategoryService.list(new QueryWrapper<ScComboCategory>().eq(ScComboCategory.SUB_CATEGORY_ID, subCategoryId).eq(ScComboCategory.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()));
        log.info("二级类目套餐={}下的商品列表",list);
        List<Long> goodsIds = list.stream().map(ScComboCategory::getGoodsId).collect(Collectors.toList());

        ScGoods goods = scGoodsService.getOne(new QueryWrapper<ScGoods>().eq(ScGoods.SUB_CATEGORY_ID, subCategoryId).in(ScGoods.ID, goodsIds).eq(ScGoods.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode())
                .orderByDesc(ScGoods.SALE_PRICE).last("limit 1"));
        log.info("二级类目当前套餐下价格最高的商品={}",goods);

        List<ScGoods> highPriceGoods = scGoodsService.list(new QueryWrapper<ScGoods>()
                .eq(ScGoods.SUB_CATEGORY_ID, subCategoryId)
                .eq(ScGoods.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode())
                .eq(ScGoods.TYPE, 1)
                .gt(ScGoods.SALE_PRICE, goods.getSalePrice()));

        if (highPriceGoods.isEmpty()) Collections.emptyList();
        List<GoodsUpgradeResponse> responses = new ArrayList<>();
        for (ScGoods highPrice : highPriceGoods) {
            GoodsUpgradeResponse response = new GoodsUpgradeResponse();
            response.setId(highPrice.getId());
            response.setName(highPrice.getName());
            response.setUpgradePrice(highPrice.getSalePrice().subtract(goods.getSalePrice()));
            response.setMainImg(highPrice.getMainImg());
            response.setLabel(highPrice.getLabel());
            responses.add(response);
        }
        return responses;
    }

    @Override
    public BaseResponse goodsMatch(Long subCategoryId) {
        List<ScGoodsMatch> list = scGoodsMatchService.list(new QueryWrapper<ScGoodsMatch>().eq(ScGoodsMatch.SUB_CATEGORY_ID, subCategoryId).eq(ScGoodsMatch.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()));
        List<CategoryMatchResponse> responses = new ArrayList<>();
        for (ScGoodsMatch match : list) {
            ScGoods goods = scGoodsService.getOne(new QueryWrapper<ScGoods>().eq(ScGoods.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()).eq(ScGoods.ID, match.getGoodsId()));
            if (ObjectUtil.isNotNull(goods)) {
                CategoryMatchResponse response = new CategoryMatchResponse();
                response.setGoodsId(match.getGoodsId());
                response.setName(goods.getName());
                response.setGoodsImg(goods.getMainImg());
                response.setSalePrice(goods.getSalePrice());
                responses.add(response);
            }
        }
        return BaseResponse.success(responses);
    }

    //查询该商品在二级分类下的价格是不是最高的
    private boolean selectUpgrade(Long subCategoryId, List<ScComboCategory> twoCategoryList) {
        ScGoods goods = scGoodsService.getOne(new QueryWrapper<ScGoods>().eq(ScGoods.SUB_CATEGORY_ID, subCategoryId).eq(ScGoods.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode())
                .orderByDesc(ScGoods.SALE_PRICE).last("limit 1"));
        log.info("该二级分类下最高价格的商品={}", JSONUtil.toJsonStr(goods));
        List<Long> subCategoryGoodsIds = twoCategoryList.stream().map(ScComboCategory::getGoodsId).collect(Collectors.toList());
        ScGoods comboGoods = scGoodsService.getOne(new QueryWrapper<ScGoods>().eq(ScGoods.IS_DELETE, NotDeteteEnum.NOT_DELETE.getCode()).in(ScGoods.ID, subCategoryGoodsIds)
                .orderByDesc(ScGoods.SALE_PRICE).last("limit 1"));
        //
        log.info("该套餐下最高价格的商品={}", comboGoods);
        if (null == goods || null == comboGoods) return false;
        if (goods.getSalePrice().compareTo(comboGoods.getSalePrice()) >=0) return true;
        return false;
    }
}
